<?php

require_once 'Pipes/Controller.php';
require_once 'Pipes/User/Auth/OpenID.php';
require_once 'Pipes/Value/BaseUrl.php';
require_once 'PEAR/Auth/OpenID/Consumer.php';
require_once 'PEAR/Auth/OpenID/FileStore.php';
require_once 'PEAR/Services/Yadis/XML.php';

define('Auth_OpenID_NO_MATH_SUPPORT', true);

class PipesCore_Controllers_AuthController extends Pipes_Controller
{
	private $_consumer = null;
	private $_auth = null;
	
	public function __construct(PipesImpl_Config $config) {
		session_start();
		parent::__construct($config);
	}
	
	public function actionLogin($returnUrl = null) {
		$_SESSION['Pipes']['_misc']['returnUrl'] = $returnUrl;
	}

	public function actionLogout() {
		$_SESSION['Pipes']['User']['Credentials'] = array();
	}

	public function actionProcess() {
		$baseUrl = new Pipes_Value_BaseUrl();

		$return = $baseUrl->value . $this->_view->action('finishAuth', $this);
		$trust = $baseUrl->value . $this->_config->base_uri;
		
		$auth = new Pipes_User_Auth_OpenID();
		$auth->process($_POST['identity_url'], $return, $trust);
	}

	public function actionFinishAuth() {
		$auth = new Pipes_User_Auth_OpenID($_GET);

		$this->_view->identity = $auth->identity_url;
		switch ($auth->status) {
			case Auth_OpenID_CANCEL :
				$this->_view->status = 'Cancelled';
				break;

			case Auth_OpenID_FAILURE :
				$this->_view->status = 'Failed!';
				break;

			case Auth_OpenID_SUCCESS :
				$this->_view->status = 'Success!';
				// auth is valid, mark it in the session:
				session_regenerate_id();
				$_SESSION['Pipes']['User']['Credentials']['isValid'] = true;
				$_SESSION['Pipes']['User']['Credentials']['identity'] = $auth->identity_url;
				break;
		}

		$returnUrl = urldecode($_SESSION['Pipes']['_misc']['returnUrl']);
		unset($_SESSION['Pipes']['_misc']['returnUrl']);
		session_write_close();

		header('Location: ' . $returnUrl);
		exit;
	}
}
